import json

from django.shortcuts import render
from django.http.response import HttpResponse
from course.models import Course


# Create your views here.

class CourseInfo:
    def __init__(self, id, name, score):
        self.id = id
        self.name = name
        self.score = score

    def __str__(self):
        return str({
            "id": self.id,
            "name": self.name,
            "score": self.score
        })


def getCourses(request):
    """
    获取所有课程信息

    :param request:
    :return: 所有课程信息的数组
    """
    courses = []
    all_students = Course.objects.all()
    for i in all_students:
        s = str(
            CourseInfo(i.pk, i.course_name, i.course_score))
        courses.append(s)
    return HttpResponse(json.dumps(courses))


def createCourse(request):
    if request.method != "POST":
        return
    data = json.loads(request.body)
    try:
        c = Course.objects.create(course_number=data.get("id"), course_name=data.get("name"),
                                  course_score=data.get("score"))
        c.save()
        return HttpResponse("创建成功")
    except BaseException as e:
        print(e)
        return HttpResponse("创建失败")


def deleteCourse(request):
    """
    删除课程

    :param request: request必须为POST，参数必须包含要删除的课程的id
    :return: 删除状态
    """
    if request.method == "GET":
        return
    data = json.loads(request.body)
    if not data.get("id"):
        return HttpResponse("请输入课程编号")
    try:
        s = Course.objects.get(course_number=data.get("id"))
        s.delete()
        return HttpResponse("删除成功")
    except BaseException as e:
        print(e)
        return HttpResponse("删除失败")


def get_course(course_id):
    """
    获取单个课程信息

    :param course_id: 要获取信息的课程的id
    :return: 所有课程信息的数组
    """
    course = Course.objects.filter(course_number=course_id)[0]
    c = str(CourseInfo(course.pk, course.student_name, course.course_score))
    return c


def changeCourse(request):
    if request.method == "GET":
        return
    data = json.loads(request.body)
    try:
        course = Course.objects.filter(course_number=data.get("id"))
        course.update(
            course_name=data.get("name"),
            course_score=data.get("score")
        )
        return HttpResponse(get_course(data.get("id")))
    except BaseException as e:
        print(e)
        return HttpResponse("修改失败")
